<?php

namespace app\api\controller\ykjp\purchase;

use app\common\controller\Api;
use think\Db;

/**
 * 退货管理
 *
 * @icon fa fa-circle-o
 */
class Retire extends Api {

    /**
     * Retire模型对象
     * @var \app\admin\model\ykjp\purchase\Retire
     */
    protected $model = null;
    protected $noNeedRight = '*';

    public function _initialize() {
        parent::_initialize();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 录单
     */
    public function add() {

        $this->model = new \app\admin\model\ykjp\purchase\Retire;
        $this->Product = new \app\admin\model\ykjp\purchase\Retprodcut;
        $param = input('post.');
        $time = time();
        $code = 'TH' . $time;

        $this->model->insert([
            'supplier_id' => $param['supplier_id'],
            'warehouse_id' => $param['warehouse_id'],
            'totalnums' => $param['totalnums'],
            'money' => $param['money'],
            'status' => $param['status'],
            'admin_id' => $param['admin_id'],
            'remark' => $param['remark'],
            'billing_time' => $time,
            'createtime' => $time,
            'updatetime' => $time,
            'code' => $code
        ]);

        $info = $this->model->where('createtime',$time)->find();

        $param['product_price'] = explode(',',$param['product_price']);
        $param['product_id'] = explode(',',$param['product_id']);
        $param['product_nums'] = explode(',',$param['product_nums']);
        $param['product_remarks'] = explode(',',$param['product_remarks']);
        $param['product_unit'] = explode(',',$param['product_unit']);
        $param['product_wait_nums'] = explode(',',$param['product_wait_nums']);

        //规格验证
        foreach ( $param['product_price'] as $k=>$v) {
           $this->Product->insert([
                'retire_id'  =>  $info['id'],
                'product_id' =>  $param['product_id'][$k],
                'warehouse_id' => $param['warehouse_id'],
                'price' =>  $param['product_price'][$k],
                'nums' =>  $param['product_nums'][$k],
                'status' =>  0,
                'subtotal' =>  $param['product_price'][$k] * $param['product_nums'][$k],
                'unit' =>  $param['product_unit'][$k],
                'remark' =>  $param['product_remarks'][$k],
                'createtime' => $time,
                'updatetime' => $time
            ]);
        }

        $this->success('返回成功');
    }


    /**
     * 查看
     */
    public function index() {
        $this->model = new \app\admin\model\ykjp\purchase\Retire;
        $info = $this->model->select();
        foreach ( $info as $k=>$v) {
            $supplier = Db('ykjp_info_supplier')->where('id',$info[$k]['supplier_id'])->value('name');
            $info[$k]['supplier'] = $supplier;
        }
        $this->success('返回成功',['data' => $info]);
    }

    /**
     * 删除
     */
    public function del($ids = null) {
        if ($ids) {
            if ($this->request->isAjax()) {
                $deltial = $this->model->where("id", "in", $ids)->where("firmid", $this->auth->firmid)->field("id")->select();
                $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
                if ($deltial) {
                    $count = 0;
                    foreach ($deltial as $key => $val) {
                        $data = array('deletetime' => time());
                        $del = $this->model->where("firmid", $this->auth->firmid)->where("id", $val['id'])->update($data);
                        $count += $del;
                        if ($del) {
                            $resProModel->where("firmid", $this->auth->firmid)->where("retire_id", $val['id'])->update($data);
                        }
                    }
                    if ($count) {
                        $this->success();
                    }
                    $this->error(__('Operation fail'));
                }
            }
            $this->error(__('Illegal operation'));
        }

        $this->error(__('Parameter %s can not be empty', "ids"));
    }

    /**
     * 详情
     */
    public function detail($ids) {
        if ($ids) {
            $detail = $this->model->with(['supplier'])->where("retire.id", $ids)->where("retire.firmid", $this->auth->firmid)->select();
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            $product = [];
            if ($detail) {
                $product = $resProModel->with(['products'])->where("retprodcut.firmid", $this->auth->firmid)->where("retire_id", $ids)->select();
                foreach ($product as $key => $val) {
                    $pro = json_decode($val['products']['prop']);
                    $val['products']['prop'] = $this->model->object_array($pro);
                }
            }
            $this->assign("detail", $detail);
            $this->assign("product", $product);
            return $this->view->fetch();
        }
        $this->error(__('Parameter %s can not be empty', "ids"), "ykjp/purchase/retire/index");
    }

    /**
     * 反审核
     */
    public function Anti($ids) {
        if ($ids) {
            $all = $this->model->where("id", "in", $ids)->where("firmid", $this->auth->firmid)->select();
            $time = time();
            $data = array("status" => "0", "updatetime" => $time, "reason" => null);
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            $count = 0;
            foreach ($all as $key => $val) {
                $up = $this->model->where("id", $val['id'])->update($data);
                $count += $up;
                if ($up) {
                    $data = array("status" => "0", "updatetime" => $time);
                    $resProModel->where("firmid", $this->auth->firmid)->where("retire_id", $val['id'])->update($data);
                }
            }
            if ($count) {
                $this->success();
            }
            $this->error(__('Operation fail'));
        }
        $this->error(__('Parameter %s can not be empty', "ids"), "ykjp/purchase/retire/detail");
    }

    /**
     * 编辑
     */
    public function edit($ids = "") {
        if ($ids) {
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;

            $select = $this->model->where("id", $ids)->where("firmid", $this->auth->firmid)->find();
            if (!$select) {
                $this->error(__("Please add basic information such as suppliers", "ykjp/purchase/retire/index"));
            }
            if ($select['status'] != "0") {
                $this->error(__("Not editable", "ykjp/purchase/retire/detail"));
            }
            if ($this->request->isAjax()) {
                $row = $this->request->param("row/a");
                $product = $this->request->param("product/a");

                if (!$row) {
                    $this->error(__("Please add basic information such as suppliers"));
                }
                if (!$product) {
                    $this->error("Please add product");
                }
                $select = $this->model->where("id", $ids)->where("firmid", $this->auth->firmid)->find();
                if (!$select) {
                    $this->error(__("Please add basic information such as suppliers"));
                }
                if ($select['status'] != "0") {
                    $this->error(__("Not editable"));
                }
                $all = json_decode($product[0]);
                $tep = $this->model->object_array($all);
                if (!$tep) {
                    $this->error("Please add product");
                }
                $row['status'] = "0";
                $updatetime = time();
                $row['billing_time'] = strtotime($row['billing_time']);
                $row['updatetime'] = $updatetime;
                $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
                $up = $this->model->where("id", $ids)->update($row);
                if ($up) {
                    $where = [];
                    $count = 0;
                    foreach ($tep as $key => $val) {
                        $data_id = $val['data_id'];
                        unset($val['data_id']);
                        $val['warehouse_id'] = $row['warehouse_id'];
                        //先查询是否存在
                        if ($data_id != "") {
                            $val['updatetime'] = $updatetime;
                            $updateWhere = array(
                                "firmid" => $this->auth->firmid,
                                "id" => $data_id,
                                "retire_id" => $ids
                            );
                            $update = $resProModel->where($updateWhere)->update($val);
                            if ($update) {
                                $count += 1;
                                $where[] = $data_id;
                            }
                        } else {
                            $val['retire_id'] = $ids;
                            $val['warehouse_id'] = $row['warehouse_id'];
                            $val['createtime'] = $updatetime;
                            $val['updatetime'] = $updatetime;
                            $val['status'] = "0";
                            $val['firmid'] = $this->auth->firmid;
                            $ins = $resProModel->insertGetId($val);
                            if ($ins) {
                                $count += 1;
                                $where[] = $ins;
                            }
                        }
                    }
                    if ($where) {
                        $del = $resProModel->where("retire_id", $ids)->where("firmid", $this->auth->firmid)->where("id", "not in", $where)->update(array("deletetime" => time()));
                    }
                    if ($count) {
                        $this->success(null, null, array('result' => "success"));
                    }
                    $this->error(__('Operation fail'));
                }
            }
            $detail = $this->model->with(['supplier'])->where("retire.id", $ids)->where("retire.firmid", $this->auth->firmid)->select();
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            $product = [];
            if ($detail) {
                $product = $resProModel->with(['products'])->where("retprodcut.firmid", $this->auth->firmid)->where("retire_id", $ids)->select();
                if ($product) {
                    foreach ($product as $key => $val) {
                        $pro = json_decode($val['products']['prop']);
                        $val['products']['prop'] = $this->model->object_array($pro);
                    }
                }
            }
            $this->assign("detail", $detail);
            $this->assign("product", $product);
            return $this->view->fetch();
        }
        $this->error(__('Parameter %s can not be empty', "ids"), "ykjp/purchase/retire/detail");
    }

    /**
     * 确认退货
     */
    public function confirm($ids = "") {
        if ($ids) {
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            if ($this->request->isAjax()) {
                $type = $this->request->param("type");
                if (!$type) {
                    $this->error(__('Parameter %s can not be empty', "type"));
                }
                //验证查询提交的对象是否已经通过审核
                $all = $this->model->where("firmid", $this->auth->firmid)->where("status", "1")->where("id", "in", $ids)->select();
                if ($all) {
                    $count = 0;
                    if ($type == "yes") {
                        foreach ($all as $key => $val) {
                            $data = array("updatetime" => time(), "status" => "3");
                            $up = $this->model->where("id", $val['id'])->update($data);

                            if ($up) {

                                $upProduct = $resProModel->where("retire_id", $val['id'])->update($data);
                                $count += $upProduct;
                                if (!$upProduct) {
                                    $count -= 1;
                                    $this->model->where("id", $val['id'])->update(array('status' => "1"));
                                }
                                if ($count) {
                                    $this->success(null, null, array("result" => "success"));
                                }
                                $this->error(__('Operation fail'));
                            }
                        }
                    } else if ($type == "no") {
                        $txt = $this->request->param("why");
                        // var_dump($txt);exit;
                        $count = 0;
                        foreach ($all as $key => $val) {
                            $updatetime = time();
                            $data = array("updatetime" => $updatetime, "status" => "4", "why" => $txt);
                            $up = $this->model->where("id", $val['id'])->update($data);
                            if ($up) {
                                $update = $resProModel->where("retire_id", $val['id'])->update(array("updatetime" => time(), "status" => "4"));
                                $count += $update;
                                if (!$update) {
                                    $data = array("status" => "1", "why" => "");
                                    $count -= 1;
                                    $this->model->where("id", $val['id'])->update($data);
                                }
                            }
                        }
                        if ($count) {
                            $this->success(null, null, array("result" => "success"));
                        }
                        $this->error(__('Operation fail'));
                    }
                }
            }
            $this->error(__('Operation fail'));
        }
        $this->error(__('Parameter %s can not be empty', "ids"));
    }

}
